package com.StarStudio.Controller;


import com.StarStudio.Service.GoodsService;
import com.StarStudio.Service.RemoteFileService;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.QueryPageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
@RestController
//@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 条件查询 商品分页接口
     * @param goods 商品对象
     * @return 分页结果对象 PageResult
     */
    @GetMapping("/page")
    public PageResult page(Goods goods){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<Goods> goodsList;
        long allRecordNumber;
        try {
            goodsList = goodsService.findGoodsList(goods);
            allRecordNumber = goodsService.findAllRecordNumber();
            pageInfo = new PageInfo<>(goodsList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS, pageInfo.getTotal(), goodsList, allRecordNumber);
    }

    /**
     * 获取商品简要信息集合
     * @return 结果对象 Result
     */
    @GetMapping("/choose_info")
    public Result getGoodsChooseResultList(){
        List<GoodsChooseResult> goodsChooseResults;
        try {
            goodsChooseResults =  goodsService.getGoodsChooseResultList();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_GOODS_INFO_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_GOODS_INFO_SUCCESS,goodsChooseResults);
    }

    /**
     * 根据商品ID查找商品
     * @param id 商品ID
     * @return 结果对象 Result
     */
    @GetMapping("/{id}")
    public Result findGoodsById(@PathVariable long id){
        Goods byGoodsId;
        try {
            byGoodsId = goodsService.findByGoods_id(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.QUERY_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_GOODS_SUCCESS,byGoodsId);
    }

    /**
     * 根据商品个体ID查询对应商品信息
     * @param goods_item_id 商品个体ID
     * @return 结果对象
     */
    @GetMapping("/by_item_id/{goods_item_id}")
    public Result findGoodsByGoodsItemId(@PathVariable long goods_item_id){
        Goods byGoods_item_id;
        try {
            byGoods_item_id = goodsService.findByGoods_Item_Id(goods_item_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.QUERY_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_GOODS_SUCCESS,byGoods_item_id);
    }

    /**
     * 导出商品信息到 Excel表格
     * @param response http响应
     * @param goods 商品对象
     */
    @Log(title = "商品管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Goods goods) {
        List<Goods> list = goodsService.findGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<>(Goods.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 根据商品ID删除商品（可单个删除也可批量删除）
     * @param Ids 删除的商品ID
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{Ids}")
    public Result deleteGoods(@PathVariable String Ids){
        try {
            if (Ids.contains(",")){
                String[] Id = Ids.split(",");
                for (String IdStr : Id) {
                    goodsService.DeleteGoodsById(Integer.parseInt(IdStr));
                }
            }else {
                goodsService.DeleteGoodsById(Integer.parseInt(Ids));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_GOODS_SUCCESS);
    }

    /**
     * 商品概览图片上传
     * @param file 文件对象
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.IMPORT)
    @PostMapping("/avatar")
    public Result avatar(@RequestParam("avatarfile") MultipartFile file) {
        if (!file.isEmpty()) {
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return new Result(HttpStatusCode.ERROR,"文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                return new Result(HttpStatusCode.ERROR,"文件服务异常，请联系管理员");
            }
            String url = fileResult.getData().getUrl();
            return new Result(HttpStatusCode.SUCCESS, MessageConstant.UPLOAD_IMAGE_SUCCESS, url);
        }
        return new Result(HttpStatusCode.ERROR, MessageConstant.UPLOAD_IMAGE_FAIL);
    }


    /**
     * 新增商品
     * @param goods 商品对象
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping("/post")
    public Result addGoods(@RequestBody Goods goods){
        try {
            goodsService.addGoods(goods);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_GOODS_SUCCESS);
    }

    /**
     * 修改商品
     * @param goods 商品对象
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PutMapping("/put")
    public Result updateGoods(@RequestBody Goods goods){
        try {
            goodsService.updateGoods(goods);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_GOODS_SUCCESS);
    }

    /*
     *  远程调用接口
     */
    @RequestMapping("/findByGoodsId/{goodsId}")
    Goods findByGoods_id(@PathVariable long goodsId){
        return goodsService.findByGoods_id(goodsId);
    }

    /*
     *  远程调用接口
     */
    @RequestMapping("/findStockByGoodsId/{goodsId}")
    int findStockByGoodsId(@PathVariable long goodsId){
        return goodsService.findStockByGoodsId(goodsId);
    }

    @RequestMapping("/updateGoodsStockById/{goodsId}/{stock}")
    void updateGoodsStockById(@PathVariable long goodsId,@PathVariable int stock){
        goodsService.updateGoodsStockById(goodsId,stock);
    }


    @RequestMapping("/ByGoodsItemId/{id}")
    Goods findByGoods_Item_Id(@PathVariable(value = "id") long id){
        return goodsService.findByGoods_Item_Id(id);
    }

    @RequestMapping("/GoodsPriceByGoodsId/{goods_id}")
    int findGoodsPriceByGoodsId(@PathVariable(value = "goods_id") long goods_id){
        return goodsService.findGoodsPriceByGoodsId(goods_id);
    }



}
